package com.example.demo02.utils;

import com.example.demo02.entity.Menu;
import com.example.demo02.entity.Role;
import com.example.demo02.mapper.MenuMapper;
import jakarta.annotation.Resource;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;

@Component
public class MyFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
     AntPathMatcher antPathMatcher =new AntPathMatcher();

     @Resource
     MenuMapper menuMapper;

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        String requestUrl = ((FilterInvocation) object).getRequestUrl(); //获取当前访问路径
        List<Menu> menus = menuMapper.getAllMenus(); //获取所有的权限，每个权限包括多个角色
        for (Menu menu:menus) {
            if (antPathMatcher.match(menu.getUrl(),requestUrl)) { //用户访问的URL与数据库中的权限匹配
                List<Role> roles = menu.getRoles(); //获取该权限对应的所有角色
                String[] roleArr = new String[roles.size()]; //将角色集合转化为数组
                for (int i = 0; i < roles.size(); i++) {
                    roleArr[i] = roles.get(i).getName();
                }
                return SecurityConfig.createList(roleArr); //角色数据转化为Collection<ConfigAttribute> 返回
            }
        }
        return null;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return false;
    }
}
